package com.hzm.test.config;

import com.google.common.cache.CacheBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.cache.guava.GuavaCache;
import org.springframework.cache.support.CompositeCacheManager;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

@Configuration
public class CacheManagerConfig {

    @Autowired
    private Jackson2JsonRedisSerializer jsonRedisSerializer;

    private RedisCacheManager redisCacheManager;

    private SimpleCacheManager simpleCacheManager;

    private ConcurrentMapCacheManager concurrentMapCacheManager;

    @Bean
    public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {

        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);

        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                // 缓存30分钟
                .entryTtl(Duration.ofMinutes(30))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jsonRedisSerializer));

        redisCacheConfiguration.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));

        redisCacheManager = new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);

        return redisCacheManager;
    }

    @Bean
    public SimpleCacheManager simpleCacheManager() {

        simpleCacheManager = new SimpleCacheManager();

        GuavaCache configCache = new GuavaCache("config", CacheBuilder.newBuilder().build());
        simpleCacheManager.setCaches(Arrays.asList(configCache));

        return simpleCacheManager;
    }

    @Bean
    public ConcurrentMapCacheManager concurrentMapCacheManager() {

        concurrentMapCacheManager = new ConcurrentMapCacheManager();

        concurrentMapCacheManager.setCacheNames(Arrays.asList("config"));

        return concurrentMapCacheManager;
    }
}
